/*
 * Copyright (C) 2009 Tony Gentilcore
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.scoreninja;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

/**
 * Submits scores to the scoreninja service.
 * 
 * @author tonygentilcore@gmail.com (Tony Gentilcore)
 */
public final class ScoreNinjaService extends Service {
  // Service URLs.
  private static final String SERVICE_URL = "http://scoreninja.appspot.com/";
  private static final String SUBMIT_SCORE_URL = SERVICE_URL + "submitscore?";
  private static final String SHOW_BOARD_URL = SERVICE_URL + "showboard?";

  @Override
  /* not using ipc... dont care about this method */
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    String appId = intent.getStringExtra(ScoreNinja.KEY_APP_ID);
    int newScore = intent.getIntExtra(ScoreNinja.KEY_NEW_SCORE, 0);
    String subBoard = intent.getStringExtra(ScoreNinja.KEY_SUB_BOARD);
    String scoreSignature = intent.getStringExtra(ScoreNinja.KEY_SIGNATURE);
    if (intent.hasExtra(ScoreNinja.KEY_NAME) && intent.hasExtra(ScoreNinja.KEY_COMMENTS)) {
      submitScore(appId, subBoard, newScore, intent.getStringExtra(ScoreNinja.KEY_NAME),
              intent.getStringExtra(ScoreNinja.KEY_COMMENTS), intent.getStringExtra(ScoreNinja.KEY_LOCATION),
              scoreSignature);
    } else {
      submitAnonymousScore(appId, subBoard, newScore, scoreSignature);
    }
  }

  /**
   * Call and forget to asynchronously submit an anonymous score which will be
   * used to calculate percentiles.
   * 
   * @param signature
   */
  private void submitAnonymousScore(final String appId, final String subBoard, int newScore,
          String scoreSignature) {
    new AsyncHttpRequest(SUBMIT_SCORE_URL + "id=" + appId +
            (subBoard != null ? "&sub=" + Uri.encode(subBoard) : "") + "&score="
            + newScore + "&signature=" + scoreSignature, new Handler() {
      @Override
      public void handleMessage(Message msg) {
        String response = msg.getData().getString(ScoreNinja.KEY_RESPONSE);
        SharedPreferences settings = getSharedPreferences(
                ScoreNinja.PREFS_NAME, 0);
        ScoreNinja.commitResponseToPrefs(appId, subBoard, settings, response);
      }
    });
  }

  /**
   * Makes an asynchronous request to update the board.
   * 
   * @param appId
   */
  static void requestBoard(String appId, String subBoard, Handler handler) {
    if (appId != null) {
      new AsyncHttpRequest(SHOW_BOARD_URL + "id=" + appId + (subBoard != null ? "&sub=" + Uri.encode(subBoard) : ""), handler);
    }
  }
  
  /**
   * Submit a new high score.
   * 
   * @param name
   * @param comments
   * @param signature
   */
  private void submitScore(final String appId, final String subBoard, int newScore, String name,
          String comments, String location, String signature) {
    new AsyncHttpRequest(SUBMIT_SCORE_URL +
            "id=" + appId +
            (subBoard != null ? "&sub=" + Uri.encode(subBoard) : "") +
            "&score=" + newScore +
            "&name=" + Uri.encode(name) +
            "&comments=" + Uri.encode(comments) +
            "&location=" + Uri.encode(location) +
            "&signature=" + signature, new Handler() {
      @Override
      public void handleMessage(Message msg) {
        String response = msg.getData().getString(ScoreNinja.KEY_RESPONSE);
        SharedPreferences settings = getSharedPreferences(
                ScoreNinja.PREFS_NAME, 0);
        ScoreNinja.commitResponseToPrefs(appId, subBoard, settings, response);
      }
    });
  }
}
